import { defineStore } from 'pinia'
import { getSearchData } from '../api/index'

export const useSearchStore = defineStore('search', {
  state: () => ({
    searchResults: null,
    searchHistory: JSON.parse(localStorage.getItem('searchHistory') || '[]')
  }),
  actions: {
    async handleSearch(keyWord: string) {
      // 添加搜索关键词到历史记录
      this.addSearchHistory(keyWord)
      console.log(this.searchHistory, 'this')

      try {
        const search_List = await getSearchData({ keyWord })
        console.log(search_List, 'aaaaaa')

        // 安全地访问数据，假设正确结构是 search_List.data.results
        this.$state.searchResults = search_List.data.result || []

        console.log(this.$state.searchResults, 'ssadfasf')
      } catch (error) {
        console.error('搜索失败:', error)
      }
    },
    addSearchHistory(keyWord: string) {
      if (!this.searchHistory.includes(keyWord)) {
        this.searchHistory.unshift(keyWord)
        localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory)) // 更新本地存储
      }
    },
    removeSearchHistory(keyWord: string) {
      this.searchHistory = this.searchHistory.filter((history: string) => history !== keyWord)
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory)) // 更新本地存储
    }
  }
})
